package ex4;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JButton;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.peer.KeyboardFocusManagerPeer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JRadioButton;
import javax.swing.JList;
import javax.swing.JComboBox;

public class MainFrame extends JFrame{

	private JPanel contentPane;
	private JMenuBar menuBar;
	private JMenu mnFile;
	private JMenuItem mntmQuit;
	private JPanel panelTopMainFrame;
	private JPanel panelNorthButtons;
	private JPanel panelSouthButtons;
	private JButton btnBack;
	private JButton btnForward;
	private JButton btnGO;
	private JTextField textAddressField;
	private JLabel lblAdresse;
	private JPanel panelBotMainFrame;
	private JButton btnNewButton_3;
	private JScrollPane scrollPane;
	private JTextArea textArea;
	private JScrollPane scrollPane_1;
	private JList list;
	private Controller controller = new Controller();
	private JComboBox comboBox;
	private String urlStartUp = "http://google.dk";
	private int counter;

	private ArrayList<String>historie = new ArrayList<String>();
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame frame = new MainFrame();
					frame.setVisible(true);




				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {


		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);

		menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		mnFile = new JMenu("File");
		menuBar.add(mnFile);

		mntmQuit = new JMenuItem("Quit");
		menuBar.add(mntmQuit);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.addKeyListener(controller);
		

		panelTopMainFrame = new JPanel();
		contentPane.add(panelTopMainFrame, BorderLayout.NORTH);
		panelTopMainFrame.setLayout(new BorderLayout(0, 0));

		panelNorthButtons = new JPanel();
		panelTopMainFrame.add(panelNorthButtons, BorderLayout.NORTH);
		panelNorthButtons.setLayout(new GridLayout(0, 3, 0, 0));

		btnBack = new JButton("<-- Back");
		panelNorthButtons.add(btnBack);
		if(historie.size()<=0){
			btnBack.setEnabled(false);
		}

		btnForward = new JButton("Forward -->");
		panelNorthButtons.add(btnForward);
		if(historie.size()<=0){
			btnForward.setEnabled(false);
		}

		btnGO = new JButton("GO!!?!?!");
		panelNorthButtons.add(btnGO);
		btnGO.addActionListener(controller);

		panelSouthButtons = new JPanel();
		panelTopMainFrame.add(panelSouthButtons, BorderLayout.SOUTH);
		panelSouthButtons.setLayout(new BorderLayout(0, 0));

		lblAdresse = new JLabel("Adresse");
		panelSouthButtons.add(lblAdresse, BorderLayout.NORTH);

		//		textAddressField = new JTextField();
		//		textAddressField.setText(urlStartUp);
		//		textAddressField.setHorizontalAlignment(SwingConstants.LEFT);
		//		panelSouthButtons.add(textAddressField, BorderLayout.CENTER);
		//		textAddressField.setColumns(10);

		comboBox = new JComboBox(historie.toArray());
		comboBox.setEditable(true);
		panelSouthButtons.add(comboBox, BorderLayout.SOUTH);
		comboBox.addKeyListener(controller);

		//-------------BOT

		panelBotMainFrame = new JPanel();
		contentPane.add(panelBotMainFrame, BorderLayout.SOUTH);
		panelBotMainFrame.setLayout(new BorderLayout(0, 0));

		btnNewButton_3 = new JButton("MONSTER NOT WORKING JBUTTON !?!?!");
		btnNewButton_3.setFont(new Font("Stencil", Font.PLAIN, 18));
		panelBotMainFrame.add(btnNewButton_3);

		//-------MIDT

		scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);

		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setPreferredSize(new Dimension(150, 2));
		contentPane.add(scrollPane_1, BorderLayout.EAST);

		list = new JList();
		list.addMouseListener(controller);
		scrollPane_1.setViewportView(list);





//		loadPage(urlStartUp);

	}

	public void loadPage(String urlString){

		StringBuilder sb = new StringBuilder(10000);


		try{

			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			InputStreamReader r = new InputStreamReader(url.openStream());
			BufferedReader in = new BufferedReader(r);
			String str;
			historie.add(urlString);
			counter++;

			while ((str = in.readLine()) != null) {
				sb.append(str+"\n");

			}
			in.close();
		}
		catch(Exception e){

		}

		textArea.setText(removetags(sb.toString()));
		list.setListData(findLinks(sb.toString()).toArray());

	}




	public static ArrayList<String> findLinks(String html) {
		ArrayList<String> a = new ArrayList<String>();
		Pattern p = Pattern.compile("(?s)<a .*?href=\"(.*?)\".*?>");
		Matcher m = p.matcher(html);
		while (m.find()) {
			a.add(m.group(1));
		}
		return a;
	}


	public static String removetags(String html) {
		html=html.replaceAll("(?s)<script.*?</script>","");
		html=html.replaceAll("(?s)<style.*?</style>","");
		html=html.replaceAll("(?s)<.*?>","");
		html=html.replaceAll("\n\n+", "\n");
		html=html.replaceAll("\r\n(\r\n)+", "\r\n");
		return html;
	}
	public void addHistorie(String url){
		historie.add(url);
		if(historie.size() == 0){
			btnBack.setEnabled(true);
		}
	}
	public void addHistoriePages(){
		historie.add("http://eb.dk");
		historie.add("http://bt.dk");
	}

	private class Controller implements ActionListener, MouseListener, KeyListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if(e.getSource() == btnGO){
				String url = (String)comboBox.getSelectedItem();
				historie.add(url);
				comboBox.addItem(url);


				loadPage(url);
			}
			if(e.getSource() == btnBack){
				if(historie.size() > 0){
					String url = historie.get(counter -1);
					loadPage(url);
				}
			}

			if(e.getSource() == btnForward){
				if(historie.size() > counter){
					String url = historie.get(counter + 1);
					loadPage(url);
				}
				if(historie.size() <= counter){
					btnForward.setEnabled(false);
				}

			}
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			// TODO Auto-generated method stub
			if(e.getClickCount() == 2){
				comboBox.setSelectedItem(((list.getSelectedValue())));
			}

		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			System.out.println("Any key pressed");
			int id = e.getID();
			if(id == KeyEvent.KEY_PRESSED){
				System.out.println("davs");
			}
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			
			 
			
		}


	}

	

}
